# -*- coding: utf-8 -*-
from django.db import models
import datetime
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User


class Family(models.Model):
    name = models.CharField(_('name'), max_length=200, blank=False)
    active = models.BooleanField(_('active'), default=True)

    def __unicode__(self):
        return u'%s' % (self.name)

    class Meta:
        verbose_name = _('family')
        verbose_name_plural = _('families')


class FamilyMember(models.Model):
    user = models.OneToOneField(User, blank=True, null=True,
                             verbose_name=_('user'),
                             related_name='family_member')

    family = models.ForeignKey(Family, blank=False, verbose_name=_('family'))

    active = models.BooleanField(_('active'), default=True)

    def __unicode__(self):
        return u'%s - %s' % (self.family, self.user)

    class Meta:
        verbose_name = _('family member')
        verbose_name_plural = _('family members')


class Currency(models.Model):
    name = models.CharField(_('name'), max_length=200, blank=False)
    symbol = models.CharField(_('symbol'), max_length=10, blank=False)
    family = models.ForeignKey(Family, blank=False, verbose_name=_('family'))

    def __unicode__(self):
        return u'%s (%s)' % (self.name, self.symbol.strip())

    class Meta:
        verbose_name = _('currency')
        verbose_name_plural = _('currencies')


class Account(models.Model):
    name = models.CharField(_('name'), max_length=200, blank=False)
    active = models.BooleanField(_('active'), default=True)
    family = models.ForeignKey(Family, blank=False, verbose_name=_('family'))

    CASH = 'CA'
    BANK = 'BA'
    TYPE_CHOICES = (
        (CASH, _('Cash')),
        (BANK, _('Bank')),
    )
    type = models.CharField(_('type'),
                            max_length=2,
                            choices=TYPE_CHOICES,
                            default=BANK)

    def __unicode__(self):
        return u'%s' % (self.name)

    class Meta:
        verbose_name = _('account')
        verbose_name_plural = _('accounts')


class Category(models.Model):
    ASSET = 'AC'
    LIABILITY = 'LC'
    TYPE_CHOICES = (
        (ASSET, _('Asset')),
        (LIABILITY, _('Liability')),
    )
    type = models.CharField(_('type'),
                            max_length=2,
                            choices=TYPE_CHOICES,
                            default=LIABILITY)

    name = models.CharField(_('name'), max_length=200, blank=False)
    active = models.BooleanField(_('active'), default=True)
    family = models.ForeignKey(Family, blank=False, verbose_name=_('family'))

    def __unicode__(self):
        return u'%s' % (self.name)

    class Meta:
        verbose_name = _('category')
        verbose_name_plural = _('categories')


class Subcategory(models.Model):
    category = models.ForeignKey(Category,
                                 blank=False,
                                 verbose_name=_('category'))

    name = models.CharField(_('name'), max_length=200, blank=False)
    active = models.BooleanField(_('active'), default=True)

    def __unicode__(self):
        return u'%s' % (self.name)

    class Meta:
        verbose_name = _('subcategory')
        verbose_name_plural = _('subcategories')


class AccountTransactions(models.Model):

    account = models.ForeignKey(Account, blank=False,
                                related_name='transactions_set',
                                verbose_name=_('account'))

    currency = models.ForeignKey(Currency, blank=False,
                                 verbose_name=_('currency'))

    amount = models.DecimalField(_('amount'),
                                 max_digits=22,
                                 decimal_places=2,
                                 blank=False)

    date = models.DateField(_('date'),
                            blank=False,
                            default=datetime.date.today)

    source_account = models.ForeignKey(
                               Account,
                               null=True,
                               blank=True,
                               related_name='transactions_from_account_set',
                               verbose_name=_('source account'))

    destination_account = models.ForeignKey(
                                    Account,
                                    null=True,
                                    blank=True,
                                    related_name='transactions_to_account_set',
                                    verbose_name=_('destination account'))

    EXTRACTION = 'EX'
    CASH = 'CA'
    BANK_TRANSFER = 'BT'
    DEBIT_CARD = 'DC'
    ELECTRONIC_PAYMENT = 'EP'
    CHECK = 'CH'
    TYPE_CHOICES = (
        (EXTRACTION, _('Extraction')),
        (CASH, _('Cash')),
        (BANK_TRANSFER, _('Bank Transfer')),
        (DEBIT_CARD, _('Debit Card')),
        (ELECTRONIC_PAYMENT, _('Electronic Payment')),
        (CHECK, _('Check')),
    )

    type = models.CharField(_('type'),
                            max_length=2,
                            choices=TYPE_CHOICES,
                            default=CASH)

    subcategory = models.ForeignKey(Subcategory,
                                    blank=False,
                                    verbose_name=_('subcategory'))

    description = models.TextField(_('description'),
                                   max_length=400, blank=True)

    confirmed = models.BooleanField(_('confirmed'), default=True)

    def __unicode__(self):
        type_name = ''
        for choice in self.TYPE_CHOICES:
            if choice[0] == self.type:
                type_name = choice[1]
                break

        return u'{} - {} - {}{:.2f} - {} - {}'.format(
                                              self.account.name,
                                              self.date, self.currency.symbol,
                                              self.amount, type_name,
                                              self.subcategory.name)

    class Meta:
        verbose_name = _('account transactions')
        verbose_name_plural = _('account transactions')


class CreditCard(models.Model):
    name = models.CharField(_('name'), max_length=200, blank=False)
    family = models.ForeignKey(Family, blank=False, verbose_name=_('family'))

    charge_account = models.ForeignKey(Account, blank=False,
                                       verbose_name=_('charge account'))

    currency = models.ForeignKey(Currency, blank=False,
                                 verbose_name=_('currency'))

    active = models.BooleanField(_('active'), default=True)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = _('credit card')
        verbose_name_plural = _('credit cards')


class CreditCardPurchase(models.Model):
    credit_card = models.ForeignKey(CreditCard, blank=False,
                                    verbose_name='credit card')

    installments = models.IntegerField(_('installments'), blank=False)

    purchase_date = models.DateField(_('purchase date'), blank=False,
                                     default=datetime.date.today)

    currency = models.ForeignKey(Currency, blank=False,
                                 verbose_name=_('currency'))

    amount = models.DecimalField(_('amount'), max_digits=22,
                                 decimal_places=2, blank=False)

    subcategory = models.ForeignKey(Subcategory, blank=False,
                                    verbose_name=_('subcategory'))

    fully_paid = models.BooleanField(_('fully paid'), default=False)
    description = models.CharField(_('description'),
                                   max_length=400, blank=True)

    def __unicode__(self):
        return u'{} - {} - {}{:.2f} - {}'.format(
                         self.credit_card, self.purchase_date, self.currency,
                         self.amount, self.installments)

    class Meta:
        verbose_name = _('credit card purchase')
        verbose_name_plural = _('credit card purchases')


class CurrencyQuote(models.Model):

    date = models.DateField(_('date'), blank=False,
                            default=datetime.date.today)

    from_currency = models.ForeignKey(
                              Currency, blank=False,
                              related_name='from_currency_quote_set',
                              verbose_name=_('from currency'))

    to_currency = models.ForeignKey(Currency, blank=False,
                                    related_name='to_currency_quote_set',
                                    verbose_name=_('to currency'))

    buy_price = models.DecimalField(_('buy price'), max_digits=22,
                                    decimal_places=4, blank=False)

    sell_price = models.DecimalField(_('sell price'), max_digits=22,
                                     decimal_places=4, blank=False)

    source = models.CharField(_('source'), max_length=200, blank=False)

    class Meta:
        verbose_name = _('currency quote')
        verbose_name_plural = _('currency quotes')


class CreditCardSummary(models.Model):
    credit_card = models.ForeignKey(CreditCard, blank=False,
                                    verbose_name=_('credit card'))

    closing_date = models.DateField(_('closing date'), blank=False)
    due_date = models.DateField(_('due date'), blank=False)

    amount = models.DecimalField(_('amount'),
                                  max_digits=22, decimal_places=2, blank=False)

    payment_transaction = models.ForeignKey(AccountTransactions, blank=True,
                            null=True, verbose_name=_('payment transaction'))

    currencyQuotes = models.ManyToManyField(
                                    CurrencyQuote,
                                    blank=True,
                                    null=True,
                                    verbose_name=_('currency quotes'))

    class Meta:
        verbose_name = _('credit card summary')
        verbose_name_plural = _('credit card summaries')


class CreditCardTransaction(models.Model):
    installment = models.IntegerField(_('installment'), blank=False)
    amount = models.DecimalField(_('amount'), max_digits=22,
                                 decimal_places=2, blank=False)

    credit_card_purchase = models.ForeignKey(CreditCardPurchase, blank=False,
                                        verbose_name=_('credit card purchase'))

    credit_card_summary = models.ForeignKey(CreditCardSummary, blank=True,
                                        verbose_name=_('credit card summary'))

    def __unicode__(self):
        installment_total_number = 1
        if self.credit_card_purchase:
            installment_total_number = (self.credit_card_purchase
                                        .installment_total)

        return u'{} - {} - {}{:.2f} - {}/{}'.format(
                self.account.name, self.type.name,
                self.currency.symbol.strip(), self.amount,
                self.installment_number, installment_total_number)

    class Meta:
        verbose_name = _('credit card transaction')
        verbose_name_plural = _('credit card transactions')


class AutomaticDebitCreditCard(models.Model):
    credit_card = models.ForeignKey(CreditCard, blank=False,
                                    verbose_name=_('credit card'))

    currency = models.ForeignKey(Currency, blank=False,
                                 verbose_name=_('currency'))

    amount = models.DecimalField(_('amount'), max_digits=22,
                                 decimal_places=2, blank=False)

    subcategory = models.ForeignKey(Subcategory, blank=False,
                                    verbose_name=_('subcategory'))

    description = models.TextField(_('description'),
                                   max_length=400, blank=True)

    active = models.BooleanField(_('active'), default=True)

    class Meta:
        verbose_name = _('automatic debit credit card')
        verbose_name_plural = _('automatic debits by credit card')


class AutomaticDebitAccount(models.Model):

    account = models.ForeignKey(Account, blank=False,
                                verbose_name=_('account'))

    currency = models.ForeignKey(Currency, blank=False,
                                 verbose_name=_('currency'))

    amount = models.DecimalField(_('amount'), max_digits=22,
                                 decimal_places=2, blank=False)

    subcategory = models.ForeignKey(Subcategory, blank=False,
                                    verbose_name=_('subcategory'))

    description = models.TextField(_('description'),
                                   max_length=400, blank=True)

    active = models.BooleanField(_('active'), default=True)

    class Meta:
        verbose_name = _(u'automatic debit account')
        verbose_name_plural = _(u'automatic debits accounts')
